package ro.unibuc.hobbygroups.controllers.xml;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import ro.unibuc.hobbygroups.domain.Group;
import ro.unibuc.hobbygroups.domain.xml.GroupList;
import ro.unibuc.hobbygroups.service.GroupsService;
import ro.unibuc.hobbygroups.service.PicturesService;

public class XMLRequestsController extends MultiActionController {

	private GroupsService groupsService;
	private PicturesService picturesService;
	
	@Autowired
	private View groupXMLView;
	
	public ModelAndView getGroups(HttpServletRequest request, HttpServletResponse response) {
		List<Group> groups = groupsService.findAll();
		
		String thumbnailUrl = getServerUrl(request) + "/download.htm?id=%1$s&thumb=true";
		String downloadUrl = getServerUrl(request) + "/download.htm?id=%1$s";

//		ro.unibuc.hobbygroups.domain.xml.Group result = 
//			ro.unibuc.hobbygroups.domain.xml.Group.fromDomain(groups.get(0), pictures.get(0), downloadUrl, thumbnailUrl);
		
		//return new ModelAndView(groupXMLView, "object", result);
		
		List<ro.unibuc.hobbygroups.domain.xml.Group> result = GroupList.fromDomain(groups, downloadUrl, thumbnailUrl);
		GroupList list = new GroupList(result);
		return new ModelAndView(groupXMLView, "groups", list);
	}

    public static String getServerUrl(HttpServletRequest request) {

        String scheme = request.getScheme();                // http
        String serverName = request.getServerName();        // localhost
        int serverPort = request.getServerPort();           // 8080
        String contextPath = request.getContextPath();      // /hobbygroups
        // String servletPath = request.getServletPath();   // /servlet/MyServlet
        // String pathInfo = req.getPathInfo();             // /a/b;c=123
        // String queryString = req.getQueryString();       // d=789

        // Reconstruct original requesting URL
        String url = scheme + "://" + serverName + ":" + serverPort + contextPath;

        // pathInfo += servletPath;
        //if (pathInfo != null) {
        //    url += pathInfo;
        //}
        //if (queryString != null) {
        //    url += "?" + queryString;
        //}
        return url;
    }
	
	@Required
	public void setGroupsService(GroupsService groupsService) {
		this.groupsService = groupsService;
	}

	@Required
	public void setPicturesService(PicturesService picturesService) {
		this.picturesService = picturesService;
	}
	
	
}
